#include <string>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

using std::string;
using namespace httplib;
using namespace ns_control;
static Control *ctrl_ptr = nullptr;

void Recover(int signo)
{
    ctrl_ptr->RecoverMachine();
}

int main()
{
    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;

    signal(SIGQUIT,Recover);

    // 获取所有题目列表
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
            { 
                string html;
                ctrl.AllQuestions(&html);
                resp.set_content(html, "text/html;charset=UTF-8;"); });
    // 获取指定题号题目
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
            {
                string number = req.matches[1];
                string html;
                ctrl.NumQuestion(number,&html);
                resp.set_content(html,"text/html;charset=UTF-8;"); });
    // 用户提交代码,进行判题
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
             {
                string number = req.matches[1];
                string res_json = "";
                ctrl.Judge(number, req.body, &res_json); 
                resp.set_content(res_json,"application/json;charset=UTF-8;"); });

    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);
    return 0;
}